<?php

declare(strict_types=1);
/**
 * This file is part of bearing-web.
 *
 * @link     https://www.bearing.cn/
 * @contact  tech@bearing.cn
 * @license  https://gitee.com/cppo/bearing_web/-/blob/master/README.md
 */

namespace frontend\controllers;

use common\CacheKey;
use yii\base\DynamicModel;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\ServerErrorHttpException;

class ProductsController extends BaseController
{
    public $modelClass = 'common\models\ProductModel';

    public function actions(): array
    {
        return ArrayHelper::merge(
            parent::actions(),
            [
                'index' => [
                    'dataFilter' => [
                        'class' => 'yii\data\ActiveDataFilter',
                        'searchModel' => function () {
                            return (new DynamicModel([
                                'cate_id' => [],
                            ]))->addRule('cate_id', 'required');
                        },
                    ],
                ],
                'view' => [
                    'class' => 'frontend\actions\ProductViewAction',
                ],
            ]
        );
    }

    /**
     * @param mixed $action
     * @throws BadRequestHttpException|ServerErrorHttpException
     */
    public function beforeAction($action): bool
    {
        if ($action->id == 'index') {
            $params = \Yii::$app->request->getQueryParams();
            if (empty($params['filter']['cate_id'])) {
                throw new ServerErrorHttpException(\Yii::t('yii', 'Param error.'));
            }
            $cateId = \Yii::$app->redis->hget(CacheKey::PRODUCT_CATE_IDS_HASH, $params['filter']['cate_id']);
            if (! $cateId) {
                throw new ServerErrorHttpException(\Yii::t('yii', 'Cate error.'));
            }
            \Yii::$app->request->setQueryParams(ArrayHelper::merge($params, ['filter' => ['cate_id' => explode(',', $cateId)]]));
        }
        return parent::beforeAction($action);
    }
}
